using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Activa.CoolStorage;
using CodeStory.Core;
using CodeStory.Core.Authentication;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.UI;
using CodeStory.WebControls;
using CodeStory.Core.ObjectBusiness;

namespace CodeStory.WebApplication.Modules.Core.Admin
{
	[NavigationPortlet("CodeStory_Core_Admin_PermissionManager")]
	public partial class PermissionManager : Portlet, IHierarchyDataSelector
	{
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);
			Load += new EventHandler(Portlet_Load);
			//treeGrid.RowDataBound += new TreeGridEventHandler(TreeGrid_RowDataBound);
			treeGrid.RowCreated += new TreeGridEventHandler(TreeGrid_RowCreated);
			btnUpdateAll.Click += new EventHandler(ButtonUpdateAll_Click);
		}

		void ButtonUpdateAll_Click(object sender, EventArgs e) {
			foreach (TreeGridRow row in treeGrid.Rows) {
				UpdatePermission(row);
			}
		}

		private void UpdatePermission(TreeGridRow row) {
			Control panel = row.FindControl("permissionPanel");
			long permission = 0;
			foreach (Control ctrl in panel.Controls) {
				CheckBox chk = ctrl as CheckBox;
				if (chk == null) continue;
				if (!chk.Checked) continue;
				int position = int.Parse(chk.Attributes["position"]);
				permission |= (uint)(1 << position);
			}
			string resourceID = string.Empty;
			Label lbl2 = row.FindControl("resourceID") as Label;
			if (lbl2 != null) {
				resourceID = lbl2.Text;
			}
			RoleResourceBusiness.InsertOrUpdateRoleResource(RoleID,new Guid(resourceID),permission);
		}

		private void TreeGrid_RowCreated(object sender, TreeGridEventArgs e) {
			string resourceType = string.Empty;
			Label lbl = e.Row.FindControl("resourceType") as Label;
			if (lbl != null) {
				resourceType = lbl.Text;
			}
			string resourceID = string.Empty;
			Label lbl2 = e.Row.FindControl("resourceID") as Label;
			if (lbl2 != null) {
				resourceID = lbl2.Text;
			}
			Control panel = e.Row.FindControl("permissionPanel");

			if (RoleID != Guid.Empty) {
				//RoleResourceObject r = RoleResourceObject.ReadFirst("RoleID=@RoleID AND ResourceID=@ResourceID", "@RoleID", RoleID, "@ResourceID", resx.ResourceID);
			} else {
			}
			long permission = RoleResourceBusiness.GetRolePermission(RoleID,new Guid(resourceID));
			Descriptor descriptor = DescriptorService.GetDescriptor(resourceType);
			foreach (ActionDescriptor adesc in descriptor.List) {
				CheckBox chk = new CheckBox();
				panel.Controls.Add(chk);
				chk.ID = "chk" + e.Row.RowIndex + adesc.Position;
				chk.Attributes["position"] = adesc.Position.ToString();
				chk.Text = adesc.Description;
				long a = 1 << adesc.Position;
				bool b = ((permission & a) == a);
				chk.Checked = b;
			}
		}

		private Guid _roleid = Guid.Empty;
		private Guid RoleID {
			get {
				if (_roleid == Guid.Empty) {
					string roleid = Request.QueryString["roleid"];
					try {
						_roleid = new Guid(roleid);
					} catch (Exception) {
						_roleid = Guid.Empty;
					} 
				}
				return _roleid;
			}
			set { _roleid = value; }
		}

		private void Portlet_Load(object sender, EventArgs e) {
			string roleid = Request.QueryString["roleid"];
			if (string.IsNullOrEmpty(roleid) && !EditMode) {
				throw new NeedQueryStringException("roleid");
			}
			if (!IsPostBack) {
				BindTreeGrid();
			}
		}

		private void BindTreeGrid() {
			treeGrid.DataSource = new TreeGridDataSource(this);
			treeGrid.DataBind();
		}

		#region IHierarchyDataSelector Members
		public ITreeGridDataObject[] SelectData(string path) {
			Guid id = Guid.Empty;
			//string parentStr = id.ToString();
			if (!string.IsNullOrEmpty(path) && path.Trim() != "/") {
				int pos = path.LastIndexOf("/");
				string str = path.Substring(pos + 1);
				//parentStr = path.Substring(0, pos);
				id = new Guid(str);
			}
			CSList<ResourceObject> list = ResourceObject.List("ParentResourceID=@ParentResourceID", "@ParentResourceID", id);
			ITreeGridDataObject[] arr = new ITreeGridDataObject[list.Count];
			int i = 0;
			foreach (ResourceObject r in list) {
				TreeGridDataObject d = new TreeGridDataObject(r, r.ResourceID, path, this);
				arr[i] = d;
				i++;
			}
			return arr;
		}

		public ITreeGridDataObject GetData(string path) {
			Guid id = Guid.Empty;
			string parentStr = id.ToString();
			if (!string.IsNullOrEmpty(path) && path.Trim() != "/") {
				int pos = path.LastIndexOf("/");
				string str = path.Substring(pos + 1);
				parentStr = path.Substring(0, pos);
				id = new Guid(str);
			}
			ResourceObject obj = ResourceObject.Read(id);
			TreeGridDataObject o = new TreeGridDataObject(obj, obj.ResourceID, parentStr, this);
			return o;
		}
		#endregion
	}
}